# @FileName  :  teacher.py
# @Time      :  2025/7/29
# @Author    :  Ayanami
# @info      :  教师相关API接口

from typing import List
from fastapi import APIRouter, HTTPException, Query, Path
from app.schemas.teacher import (
    TeacherCreate,
    TeacherUpdate,
    TeacherResponse,
    TeacherListResponse,
    TeacherQuery
)
from app.crud.teacher import teacher_crud

router = APIRouter(tags=["教师管理"])


@router.post("/", response_model=TeacherResponse, summary="创建教师")
async def create_teacher(teacher_data: TeacherCreate):
    """创建新教师"""
    try:
        teacher = await teacher_crud.create(teacher_data)
        return teacher
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建教师失败,{str(e)}")


@router.get("/", response_model=TeacherListResponse, summary="获取教师列表")
async def get_teachers(
    name: str = Query(None, description="姓名模糊查询"),
    teacher_id: str = Query(None, description="教工号查询"),
    specialty: str = Query(None, description="教学方向模糊查询"),
    category_id: int = Query(None, description="分类查询"),
    level: str = Query(None, description="职称级别查询"),
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(10, ge=1, le=100, description="返回记录数")
):
    """获取教师列表，支持多条件查询和分页"""
    query = TeacherQuery(
        name=name,
        teacher_id=teacher_id,
        specialty=specialty,
        category_id=category_id,
        level=level,
        skip=skip,
        limit=limit
    )
    teachers, total = await teacher_crud.get_list(query)
    return TeacherListResponse(total=total, items=teachers)


@router.get("/get-teacher/{teacher_id}", response_model=TeacherResponse, summary="获取教师详情")
async def get_teacher(
    teacher_id: int = Path(..., description="教师ID")
):
    """根据ID获取教师详情"""
    teacher = await teacher_crud.get_by_id(teacher_id)
    if not teacher:
        raise HTTPException(status_code=404, detail="教师不存在")
    return teacher


@router.get("/{teacher_id}", response_model=TeacherResponse, summary="根据教工号获取教师")
async def get_teacher_by_teacher_id(
    teacher_id: str = Path(..., description="教工号")
):
    """根据教工号获取教师详情"""
    teacher = await teacher_crud.get_by_teacher_id(teacher_id)
    if not teacher:
        raise HTTPException(status_code=404, detail="教师不存在")
    return teacher


@router.put("/{teacher_id}", response_model=TeacherResponse, summary="更新教师信息")
async def update_teacher(
    teacher_data: TeacherUpdate,
    teacher_id: int = Path(..., description="教师ID")
):
    """更新教师信息"""
    try:
        teacher = await teacher_crud.update(teacher_id, teacher_data)
        if not teacher:
            raise HTTPException(status_code=404, detail="教师不存在")
        return teacher
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新教师失败,{str(e)}")


@router.delete("/{teacher_id}", summary="删除教师")
async def delete_teacher(
    teacher_id: int = Path(..., description="教师ID")
):
    """删除教师"""
    success = await teacher_crud.delete(teacher_id)
    if not success:
        raise HTTPException(status_code=404, detail="教师不存在")
    return {"message": "删除成功"}


@router.get("/category/{category}", response_model=List[TeacherResponse], summary="根据分类获取教师")
async def get_teachers_by_category(
    category: int = Path(..., description="分类ID")
):
    """根据分类获取教师列表"""
    teachers = await teacher_crud.get_teachers_by_category(category)
    return teachers


@router.get("/search/{keyword}", response_model=List[TeacherResponse], summary="搜索教师")
async def search_teachers(
    keyword: str = Path(..., description="搜索关键词"),
    limit: int = Query(10, ge=1, le=50, description="返回记录数")
):
    """搜索教师（姓名、教工号、教学方向）"""
    teachers = await teacher_crud.search_teachers(keyword, limit)
    return teachers


@router.patch("/{teacher_id}/increment-sessions", summary="增加授课场次")
async def increment_sessions_count(
    teacher_id: int = Path(..., description="教师ID")
):
    """增加教师授课场次"""
    success = await teacher_crud.increment_sessions_count(teacher_id)
    if not success:
        raise HTTPException(status_code=404, detail="教师不存在")
    return {"message": "授课场次已更新"}
